<?php
/**
 * Feeds manager Component
 *
 * @package		yos_news_crawler
 * @subpackage	CMS
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');

class YOS_Cms_Joomla extends JObject {
	//object article
	private $_arr_article;
	
	//store job id key
	private $_job_configuration;
	
	public function __construct($job_configuration, $arr_article)
	{
		$this->_job_configuration = $job_configuration;
		$this->_arr_article = $arr_article;
	}
			
	//when job call store_article function,
	//-store images file
	//-build Joomla article
	//-store in database
	public function store_articles()
	{
		$db =& JFactory::getDBO();
		
		if(!$this->_get_config()){
			return false;
		}
		
		$cms_params_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'joomla'.DS.'cms_config_job.xml';
		if(!is_readable($cms_params_file)){
			$this->setError('[CMS JOOMLA] unable to load params configure file: '.$cms_params_file);
			return false;
		}
		$params = new JParameter($this->_job_configuration->params, $cms_params_file);
		$time_plus = 0;
		foreach ($this->_arr_article as &$article){
			//check article link is exist			
			$query = "SELECT COUNT(*) FROM #__yos_content_link WHERE `link` = ".$db->Quote($article->link)." 
				AND `cms` = 'joomla'";
			$db->setQuery($query);
			$is_exist = $db->loadResult();
			if ($db->getErrorNum()) {
				$arr_error = debug_backtrace();
				$this->setError('[CMS JOOMLA] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
				return false;
			}
			if ($is_exist) {
				continue;
			}
			
			$row = $this->_store_article($article, $params, $time_plus);
			$time_plus = $time_plus + 10;
			if (!$row) {
				continue;
			}
			$this->_added_fetched_article($article->link, $row);
									
			//store image...
			if ($this->_job_configuration->get_img) {
				if($this->_move_image($article->image_path, $row)){
					//update article
					$dispatcher		= &JDispatcher::getInstance();
					JPluginHelper::importPlugin('content');				
					$result	= $dispatcher->trigger('onBeforeContentSave', array (&$row, false ));
					$row->store();
					$result	= $dispatcher->trigger('onAfterContentSave', array (&$row, false ));
				}		
			}
		}
	}
	
	private function _move_image($image_path, &$row){
		//TODO: get destination image path from cms configure here
		$dest_img_path = JPATH_BASE.DS.'images'.DS.'stories'.DS.$row->id;
		$new_img_base_url = 'images/stories/'.$row->id.'/';
		if(!JFolder::create($dest_img_path)){
			$this->setError('[CMS JOOMLA] cannot create folder to store images: '.$dest_img_path);
			return false;
		}
		if (!is_writable($dest_img_path)) {
			$this->setError('[CMS JOOMLA] image path is not writable: '.$dest_img_path);
			return false;
		}
		
		$row->introtext = $this->_move_image_in_string($row->introtext, $image_path, $dest_img_path, $new_img_base_url);
		$row->fulltext = $this->_move_image_in_string($row->fulltext, $image_path, $dest_img_path, $new_img_base_url);
		
		return true;
	}
	
	private function _move_image_in_string($str_in, $image_path, $dest_img_path, $new_img_base_url){
		if (!preg_match_all('/<img.*?src="([^"]+)"[^>]*>/i', $str_in, $matches)) {
			return $str_in;
		}
		
		foreach ($matches[1] as $str_img_src){
			$file_name = JFile::getName($str_img_src);
			$file_name = urldecode($file_name);
			if (!is_readable($image_path.DS.$file_name)) {
				continue;
			}
			if(!JFile::copy($image_path.DS.$file_name, $dest_img_path.DS.$file_name)){
				continue;
			}
			$str_in = str_replace($str_img_src, $new_img_base_url.$file_name, $str_in);
		}
		
		return $str_in;
	}
	
	//get cms configuration
	private function _get_config()
	{
		$config_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'joomla'.DS.'cms_config.php';
		if(!is_readable($config_file)){
			$this->setError('[CMS JOOMLA] unable to load configure file: '.$config_file);
			return false;
		}
		require_once($config_file);
				
		$this->_image_path = $image_path;
		
		return true;
	}			
	
	//store article in database
	private function _store_article(&$obj_article, $params, $time_plus)
	{
		$db	 =& JFactory::getDBO();
		
		//add according info
		$str_source_content = $this->_job_configuration->according_to;
		//readmore (add original source link)
		if ($params->get('readmore')) {
			$str_source_content = '<a href="'.$obj_article->link.'" title="'.$this->_job_configuration->according_to.'" target="_blank">'.$this->_job_configuration->according_to.'</a>';
		}
		if ($obj_article->full_text) {
			$obj_article->full_text = $obj_article->full_text."\n".'<p class="according">'.$str_source_content.'</p>';
		}
		else {
			$obj_article->intro_text = $obj_article->intro_text."\n".'<p class="according">'.$str_source_content.'</p>';
		}
		
		
		//title ads
		if ($this->_job_configuration->title_ext) {
			if ($this->_job_configuration->title_ext_pos == 0) {
				$obj_article->title = $this->_job_configuration->title_ext . $obj_article->title;
			}
			else {
				$obj_article->title = $obj_article->title . $this->_job_configuration->title_ext;
			}			
		}
		
		//intro ads
		if ($this->_job_configuration->ads) {
			if ($this->_job_configuration->catads == 0) {
				$obj_article->intro_text = $this->_job_configuration->ads . $obj_article->intro_text;
			}
			else {
				$obj_article->intro_text = $obj_article->intro_text . $this->_job_configuration->ads;
			}			
		}
		
		$row =	&JTable::getInstance('content');
		$row->title 			= $obj_article->title;
		$row->alias 			= '';
		$row->title_alias 		= '';
		$row->introtext 		= $obj_article->intro_text;
		$row->fulltext 			= $obj_article->full_text;
		
		$row->state 			= 1;
		if ($params->get('keyword_unpublish')) {
			$str_in = $obj_article->title.$obj_article->intro_text.$obj_article->full_text;
			if(YOS_utility::test_keyword($str_in, $params->get('keyword_unpublish'))){
				$row->state = 0;
			}
		}
		
		$query = "SELECT `section` FROM #__categories WHERE `id` = ".intval($params->get('catid'));
		$db->setQuery($query);
		$section_id = $db->loadResult();
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS JOOMLA] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		if (!$section_id) {
			$this->setError('[CMS JOOMLA] unable to find section id with category id: '.intval($params->get('catid')));
			return false;
		}
		$row->sectionid 		= $section_id;
		
		$time_now		= JFactory::getDate();
		$time_now		= $time_now->toUnix() + $time_plus;//seconds
		$time_now		= strftime('%Y-%m-%d %H:%M:%S', $time_now);
		$null_date		= $db->getNullDate();
		
		$row->catid 			= $params->get('catid');
						
		if($params->get('keysave')){
			if(preg_match_all('/\[(.*?)=>(\d+)\]/', $params->get('keysave'), $matches)){
				for($i = 0; $i < count($matches[1]); $i++){
					if (preg_match('/'.preg_quote($matches[1][$i]).'/i', $obj_article->title.$obj_article->intro_text.$obj_article->full_text)) {
						$row->catid = $matches[2][$i];
						break;
					}
				}				
			}
		}
				
		$row->created 			= $time_now;
		$row->created_by 		= $params->get('created_by');
		$row->modified 			= $time_now;
		$row->modified_by 		= $params->get('created_by');
		$row->checked_out 		= 0;
		$row->checked_out_time 	= $null_date;
	
		$publish_up = strtotime($time_now) + floatval($params->get('publish_time'))*60*60;
		$publish_up = strftime('%Y-%m-%d %H:%M:%S', $publish_up);
		$row->publish_up 		= $publish_up;
		
		$publish_down = $null_date;
		if ($params->get('publish_down')) {
			$publish_down = strtotime($time_now) + floatval($params->get('publish_down'))*60*60;
			$publish_down = strftime('%Y-%m-%d %H:%M:%S', $publish_down);
		}
		$row->publish_down 		= $publish_down;
		
		$row->metakey 			= '';
		$row->metadesc 			= '';
		
		$row->access 			= $params->get('access');
		
		if (!$row->check()) {
			$this->setError('[CMS JOOMLA] row check fail: '.$row->getError());
			return false;
		}				
		$dispatcher		= &JDispatcher::getInstance();
		JPluginHelper::importPlugin('content');
		$result	= $dispatcher->trigger('onBeforeContentSave', array (&$row, true ));
		
		$row->store();
		if (!$row->id) {
			$this->setError('[CMS JOOMLA] Fail to store article: '.$row->getError());
			return false;
		}
		
		//front page:
		$front_page = false;
		if ($params->get('front_page')) {
			$front_page = true;
			if ($params->get('front_page_keyword')) {
				$front_page = false;
				$str_in = $obj_article->title.$obj_article->intro_text.$obj_article->full_text;
				if(YOS_utility::test_keyword($str_in, $params->get('front_page_keyword'))){
					$front_page = true;
				}
			}
		}
		if ($front_page) {
			$this->_set_frontpage($row->id);
		}
		$result	= $dispatcher->trigger('onAfterContentSave', array (& $row, true ));
		
		return $row;
	}
			
	private function _set_frontpage($content_id) {
		$db		=&	JFactory::getDBO();
		$query	=	"INSERT INTO #__content_frontpage SET
							content_id	=	$content_id, ordering = 0";
		$db->setQuery($query);
		$db->query();
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS JOOMLA] Fail to set front-page: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		
		return true;
	}
	
	private function _added_fetched_article($link, $row){
		$db		=&	JFactory::getDBO();
		$query	=	"INSERT INTO #__yos_content_link SET
			`link`	=	".$db->Quote($link).", 
			`title`	=	".$db->Quote($row->title).", 
			`cms`	=	".$db->Quote('joomla').", 
			`articleid`	= $row->id";
		$db->setQuery($query);
		$db->query();
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS JOOMLA] Fail to insert fetched article to list: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		
		return true;
	}

}